package com.sbl.bajw.pc.action;

import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sbl.bajw.common.ExcelUtil;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.pc.model.LogTModel;
import com.sbl.bajw.pc.model.OrderPushTModel;
import com.sbl.bajw.pc.model.UserModel;
import com.sbl.bajw.pc.service.LogTModelService;
import com.sbl.bajw.pc.service.OrderPushTModelService;
import com.sbl.bajw.pc.service.UserService;
import com.sbl.bajw.util.JsonUtil;
import com.sbl.bajw.util.LogUtil;

@Controller
@RequestMapping("/OrderPushTModel")
public class OrderPushTModelAction {
	
	@Resource
	private OrderPushTModelService service;
	
	@Resource
	private UserService userService;
	
	@Resource
	private LogTModelService logTService;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
	
	static Logger log;
	
	static{
		log = LogUtil.getLogger("OrderPush");
	}
	
	@RequestMapping(value = "/addView")
	public ModelAndView addView(){
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		String id = service.getid();
		String dateStr = df.format(Calendar.getInstance().getTime());
		String orderCode = "4403" + dateStr + id;
		
		RequestUnit.setAttr("orderCode", orderCode);
		RequestUnit.setAttr("id", id);
		ModelAndView mv = new ModelAndView("/view/OrderPush/sendDialog");
		return mv;
		
	}
	
	@RequestMapping(value = "/getOrderModelList")
	public @ResponseBody String getOrderModelList(HttpServletRequest request, HttpServletResponse response){
		String userId = request.getParameter("user_id");
		log.info(userId+"在请求指挥调度列表");
		return "";
	}
	
	@RequestMapping(value = "/downloadList")
	public void downloadList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String state = RequestUnit.getString("isfinish");
		String userId = request.getParameter("user_id");
		String title = RequestUnit.getString("title");
		String orderClass = RequestUnit.getString("orderClass");
		String orderCode = RequestUnit.getString("orderCode");
		String orderContent = RequestUnit.getString("orderContent");
		String addr = RequestUnit.getString("addr");
		String start_date = RequestUnit.getString("start_date");
		String stop_date = RequestUnit.getString("stop_date");
		
		log.info("请求指挥调度列表：state="+state+","+"userId="+userId);
		HashMap<String, Object> parm = new HashMap<String, Object>();

		if(userId != null && !"".equals(userId)){
			UserModel userModel = userService.getModel(userId);
			if(userModel!=null){
				parm.put("userName", userModel.getUsername());
			}
		}
		if(state != null && !"".equals(state)){
			parm.put("state", state);
		}
		if(title != null && !"".equals(title)){
			parm.put("title", "%"+title+"%");
		}
		if(orderClass != null && !"".equals(orderClass)){
			parm.put("orderClass",orderClass);
		}
		if(orderCode != null && !"".equals(orderCode)){
			parm.put("orderCode","%"+orderCode+"%");
		}
		if(orderContent != null && !"".equals(orderContent)){
			parm.put("orderContent","%"+orderContent+"%");
		}
		if(addr != null && !"".equals(addr)){
			parm.put("addr","%"+addr+"%");
		}
		if(start_date != null && !"".equals(start_date)){
			parm.put("start_date","%"+start_date+"%");
		}
		if(stop_date != null && !"".equals(stop_date)){
			parm.put("stop_date","%"+stop_date+"%");
		}
		
		List<HashMap<String, Object>> list = service.getOrderModelList(parm);
		LinkedHashMap<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("ORDER_TITLE", "标题");
		columns.put("ORDER_CODE", "指令编码");
		columns.put("ORDER_CLASS_TEXT", "指令等级");
		columns.put("ORDER_STATUS_TEXT", "指令状态");
		columns.put("CREATETIME", "创建时间");
		
		HSSFWorkbook wb = ExcelUtil.createExcel(list, columns);
		OutputStream outStream = response.getOutputStream();
		response.setContentType("application/x-msdownload");  
		response.setHeader("Content-Disposition","attachment;filename=data.xls");  
		wb.write(outStream);
	}
	
	@RequestMapping(value = "/add")
	public @ResponseBody String add() throws MessageException{
		OrderPushTModel model = RequestUnit.getModel(OrderPushTModel.class);
		
		model.setCreateBy(SessionUnit.getUserId());
		model.setCreatetime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		String resultStr = "";
		try {
			log.info("发布指令：model="+JsonUtil.ConvertObjectToJson(model));
			service.insert(model);
			resultStr += "{";
			resultStr += "\"code\":\"1\",";
			resultStr += "\"msg\":\"\",";
			resultStr += "\"success\":\"true\",";
			resultStr += "\"data\":{}";
			resultStr += "}";
		} catch (Exception e) {
			log.error("新增出错",e);
			throw new MessageException("新增出错", "4");
		}
		
		return resultStr;
	}
	
	@RequestMapping(value = "/Detail")
	public ModelAndView Detail(HttpServletResponse response, HttpServletRequest request){
		String id = RequestUnit.getString("id");
		HashMap<String, Object> result = service.getModel(id);
		
		ModelAndView mv = new ModelAndView("/view/OrderPush/detail");
		request.setAttribute("model", result);
		return mv;
	}
	
	@RequestMapping(value = "/getOrderPushTModel")
	public @ResponseBody String getOrderPushTModel(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String id = RequestUnit.getString("id");
		String userId = request.getParameter("user_id");
		String resultStr = "";
		try {
			log.info("获取指令详情：id="+id+",userId="+userId);
			HashMap<String, Object> model = service.getModel(id);
			String json = null;
			if(model == null){
				json = "";
			}
			else{
				if("0".equals(model.get("ORDER_READ_STATUS"))){
					service.updateReadStatus(id);
					model = service.getModel(id);
				}
				json = JsonUtil.ConvertObjectToJson(model);
			}
			resultStr += "{";
			resultStr += "\"code\":\"1\",";
			resultStr += "\"msg\":\"\",";
			resultStr += "\"success\":\"true\",";
			resultStr += "\"data\":"+json+"";
			resultStr += "}";
		} catch (Exception e) {
			log.error("获取指令详情错误", e);
			throw new MessageException("系统异常", "4");
		}
		return resultStr;
	}
	
	@RequestMapping(value = "/CompleteInstructions")
	public @ResponseBody String CompleteInstructions(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String positionX = RequestUnit.getString("position_x");
		String positionY = RequestUnit.getString("position_y");
		String address = RequestUnit.getString("address");
		String note = RequestUnit.getString("note");
		String id = RequestUnit.getString("id");
		String userId = request.getParameter("user_id");
		HashMap<String, String> json = new HashMap<String, String>();
		String str = "";
		LogTModel logT = new LogTModel();
		try {
			log.info("完成指令：id="+id+",userId="+userId+",note="+note+",positionX="+positionX+",positionY="+positionY);
			service.CompleteInstructions(id, positionX, positionY, note, address);
			Date d = new Date();
			logT.setUserid(userId);
			logT.setCode("3");
			logT.setOperatingContent(sdf.format(d) + "," + userId + "于" + address + "完成指令。");
			logTService.insert(logT);
			json.put("code", "1");
			json.put("msg", "上传成功");
			json.put("success", "true");
			str = JsonUtil.ConvertObjectToJson(json);
		} catch (Exception e) {
			log.error("完成指令出错", e);
			throw new MessageException("系统异常", "4");
		}
		return str;
	}
}
